﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LOLApi
{
    public class LcuClient : HttpClient
    {
        public HttpClient? _httpClient;
        private HttpClientHandler _handler = new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true,//绕过验证
            ClientCertificateOptions = ClientCertificateOption.Manual
        };
        private string _baseUrl = string.Empty;
        public string _port = string.Empty;
        public string _token = string.Empty;
        private readonly string CmdOrder = "wmic PROCESS WHERE name='LeagueClientUx.exe' GET commandline";
        public LcuClient()
        {
            _httpClient = InitLcuClient().Result;
        }

        public Task<HttpClient> InitLcuClient()
        {
            if (IsAdministrator())
            {
                var result = CMD(CmdOrder);
                Getportandauth(result);
                if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(_token))
                {
                    _port = _port.Remove(_port.Length - 1);
                    _port = _port.Substring(_port.IndexOf("=") + 1);
                    _token = _token.Remove(_token.Length - 1);
                    _token = _token.Substring(_token.IndexOf("=") + 1);
                    _baseUrl = "https://127.0.0.1" + $":{_port}";
                    var authTokenBytes = Encoding.ASCII.GetBytes($"riot:{_token}");
                    if (_httpClient == null) _httpClient = new HttpClient(_handler);
                    _httpClient.BaseAddress = new Uri($"{_baseUrl}");
                    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authTokenBytes));
                    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    return Task.FromResult(_httpClient);
                }

            }
            return Task.FromResult(new HttpClient(_handler));
        }
        private void Getportandauth(string output)
        {
            Regex regex = new Regex("--remoting-auth-token=(.*?)[\"'\\s]");
            Regex regex1 = new Regex("--app-port=(.*?)[\"'\\s]");
            Match match = regex.Match(output);
            Match match1 = regex1.Match(output);
            if (match.Success)
            {
                _token = match.Groups[0].Value;
            }
            if (match1.Success)
            {
                _port = match1.Groups[0].Value;
            }

        }
        public bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        public string CMD(string command)
        {
            Process pro = new Process();
            pro.StartInfo.FileName = "cmd.exe";             //cmd  
            pro.StartInfo.UseShellExecute = false;          //不显示shell  
            pro.StartInfo.CreateNoWindow = true;            //不创建窗口  
            pro.StartInfo.RedirectStandardInput = true;     //打开流输入  
            pro.StartInfo.RedirectStandardOutput = true;    //打开流输出  
            pro.StartInfo.RedirectStandardError = true;     //打开错误流  
            pro.Start();//执行  
            pro.StandardInput.WriteLine(command + "&exit");      //&exit运行完立即退出  
            pro.StandardInput.AutoFlush = true;             //清缓存  

            var str = pro.StandardOutput.ReadToEnd();            //读取输出  
            pro.WaitForExit();                              //等待程序执行完退出进程    
            pro.Close();//结束    
            return str;
        }

    }
}
